//
//  CHScreeningViewController.m
//  CarFile
//
//  Created by 陈浩 on 2017/4/5.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHScreeningViewController.h"
#import "CZDatePicker.h"
#import "NSDate+Extend.h"
#import "CHLabel.h"
#import "PJ_Model.h"
#import "CHSectionViewCell.h"
#import "CHComplainCountController.h"
@interface CHScreeningViewController ()<CZDatePickerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    BOOL isStart;
    NSString *areaid;
    NSString *areacn;
    NSIndexPath *currentIndexpath;
    
}
@property (nonatomic ,strong) UILabel *startTimeLabel;
@property (nonatomic ,strong) UILabel *endTimeLabel;
@property (nonatomic ,strong) UIButton *startBtn;
@property (nonatomic ,strong) UIButton *endBtn;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,copy) LongriseRouterBlock block;
@end

@implementation CHScreeningViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"eeeef0" alpha:1.0f];
    areaid = (NSString *)[Util getValue:@"areaid"];
    
    UILabel *timeTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(22, 0, UIScreenW - 22, 44)];
    timeTitleLabel.text = @"开始日期和结束日期";
    timeTitleLabel.font = [UIFont systemFontOfSize:16];
    timeTitleLabel.backgroundColor = [UIColor clearColor];
    timeTitleLabel.textColor = [UIColor colorWithHexString:@"148ec7" alpha:1.0f];
    [self.view addSubview:timeTitleLabel];

    

    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, UIScreenW, 105)];
    headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headView];
    
    
    
    UILabel *startTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(22, 10, 70, 40)];
    startTimeLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    startTimeLabel.text = @"开始日期:";
    startTimeLabel.font = [UIFont systemFontOfSize:14];
    [headView addSubview:startTimeLabel];
    
    CHLabel *startTime = [[CHLabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(startTimeLabel.frame), 15, UIScreenW - CGRectGetMaxX(startTimeLabel.frame) - 10, 30)];
    startTime.userInteractionEnabled = YES;
    startTime.text = @"请选择开始日期";
    startTime.layer.borderColor = [UIColor lightGrayColor].CGColor;
    startTime.layer.borderWidth = 1;
    startTime.layer.cornerRadius = 3;
    startTime.layer.masksToBounds = YES;
    startTime.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    startTime.font = [UIFont systemFontOfSize:14];
    startTime.text = self.startTime;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [startTime addGestureRecognizer:tap];
    [headView addSubview:startTime];
    self.startTimeLabel = startTime;
    

    UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake(startTime.frame.size.width - 20-10, 10, 20, 10)];
    [startBtn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
//    [startBtn addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
    [startTime addSubview:startBtn];
    self.startBtn = startBtn;

    
    
    UILabel *endTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(startTimeLabel.frame) +5, 70, 40)];
    endTitleLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    endTitleLabel.text = @"结束日期:";
    endTitleLabel.font = [UIFont systemFontOfSize:14];
    [headView addSubview:endTitleLabel];
    
    CHLabel *endTimeLabel = [[CHLabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(endTitleLabel.frame), CGRectGetMaxY(startTime.frame) +15, startTime.frame.size.width, 30)];
    endTimeLabel.userInteractionEnabled = YES;
    endTimeLabel.text = @"请选择开始日期";
    endTimeLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    endTimeLabel.layer.borderWidth = 1;
    endTimeLabel.layer.cornerRadius = 3;
    endTimeLabel.layer.masksToBounds = YES;
    endTimeLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    endTimeLabel.font = [UIFont systemFontOfSize:14];
    endTimeLabel.text = self.endTime;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [endTimeLabel addGestureRecognizer:tap1];
    [headView addSubview:endTimeLabel];
    self.endTimeLabel = endTimeLabel;
    
    UIButton *endBtn = [[UIButton alloc] initWithFrame:CGRectMake(endTimeLabel.frame.size.width - 20-10, 10, 20, 10)];
    [endBtn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
//    [endBtn addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
    [endTimeLabel addSubview:endBtn];
    
   
    UILabel *areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(headView.frame), UIScreenW - 22, 44)];
    areaLabel.text = @"行政区域选择";
    areaLabel.font = [UIFont systemFontOfSize:16];
    areaLabel.backgroundColor = [UIColor clearColor];
    areaLabel.textColor = [UIColor colorWithHexString:@"148ec7" alpha:1.0f];
    [self.view addSubview:areaLabel];
    
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(areaLabel.frame), UIScreenW, UIScreenH - CGRectGetMaxY(areaLabel.frame) - 64)];
    contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contentView];
    
  
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.itemSize = CGSizeMake((UIScreenW -15*5) /4, 30);
    UICollectionView *collectionView =  [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW,contentView.frame.size.height - 60) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.scrollEnabled = NO;
    collectionView.pagingEnabled = YES;
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsHorizontalScrollIndicator = NO;
    [collectionView registerClass:[CHSectionViewCell class] forCellWithReuseIdentifier:@"CHSectionViewCell"];
    
    
    
//    
//    NSInteger selectedIndex = 0;
//    
//    NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
//    
//    [collectionView selectItemAtIndexPath:selectedIndexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    [contentView addSubview:collectionView];
    self.collectionView = collectionView;
    
    
    
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(collectionView.frame), UIScreenW - 44, 40)];
    sureBtn.layer.cornerRadius = 5;
    sureBtn.layer.masksToBounds = YES;
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn setBackgroundColor:[UIColor colorWithHexString:@"148ec7" alpha:1.0f]];
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:sureBtn];
    
}


-(void)tapGesture:(UITapGestureRecognizer *)tap{
    
    isStart = (tap.view == self.startTimeLabel) ? YES :NO;
    // 创建日期选择器
    CZDatePicker *datePicker = [CZDatePicker datePicker];
    NSDate * date = [NSDate date];//当前时间
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];//前一天
    datePicker.maxDate = date;
    datePicker.minDate = [self getMinDate];
    datePicker.delegate = self;
    // 显示
    [datePicker show];
    
    
}


-(void)chooseTime:(UIButton *)btn{
    

    isStart = (btn == self.startBtn) ? YES :NO;
    // 创建日期选择器
    CZDatePicker *datePicker = [CZDatePicker datePicker];
    NSDate * date = [NSDate date];//当前时间
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];//前一天
    datePicker.maxDate = lastDay;
    datePicker.minDate = [self getMinDate];
    // 设置代理
    datePicker.delegate = self;
    // 显示
    [datePicker show];

}



/****
     比较日期大小默认会比较到秒
 ****/
-(int)compareOneDay:(NSString *)oneDayStr withAnotherDay:(NSString *)anotherDayStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending) {
        NSLog(@"开始日期不的大于结束日期");
        return 1;
    }
    else if (result ==NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}





-(NSDate *)getMinDate{
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    NSDate *minDate = [NSDate dateFromString:[NSString stringWithFormat:@"%zd-01-01",comp.year] formattor:@"YYYY-MM-dd"];
    return minDate;
    
}


- (void)datePicker:(CZDatePicker *)pickerView didClickBtnType:(CZKeyboardToolButtonType)type{
    
    if (type == CZKeyboardToolButtonTypeSure) { // 确定
        // 获得触发日期选择器的对象
        
        if (isStart) {
            self.startTimeLabel.text = [NSDate stringFromDate:pickerView.datePicker.date formattor:@"yyyy-MM-dd"];
        }else{
            
            self.endTimeLabel.text = [NSDate stringFromDate:pickerView.datePicker.date formattor:@"yyyy-MM-dd"];
        }
       
    }
    
}


//  确定
-(void)sureBtnClick{
    
   int restut = [self compareOneDay:self.startTimeLabel.text withAnotherDay:self.endTimeLabel.text];
    if (restut == 1) {
        [MBProgressHUD showError:@"开始日期不得大于结束日期"];
    }else{
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"areaid"] = areaid;
        dict[@"areacn"] = areacn;
        dict[@"startTime"] = self.startTimeLabel.text;
        dict[@"endTime"] = self.endTimeLabel.text;
        if (self.block) {
            self.block(dict);
        }
        [self.navigationController popViewControllerAnimated:YES];
   
    } 
}



#pragma mark - UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  [Globle getInstance].datas.count+1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"CHSectionViewCell";
    CHSectionViewCell *cell = (CHSectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.label.text = @"全部";
        cell.backgroundColor = [UIColor colorWithHexString:@"148ec7" alpha:1.0f];
        cell.label.textColor = [UIColor whiteColor];
        [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }else{
        PJ_Model *model =[Globle getInstance].datas[indexPath.row-1];
        cell.label.text = model.areacn;
    }
    return cell;
  
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 15,15);
}

-(CGFloat )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

{
    return 20;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了第%ld组的第%ld个", indexPath.section, indexPath.row);
    CHSectionViewCell *cell = (CHSectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithHexString:@"148ec7" alpha:1.0f];
    cell.label.textColor = [UIColor whiteColor];
    if (indexPath.row == 0) {
        areaid = (NSString *)[Util getValue:@"areaid"];
    }else{
        
        PJ_Model *model = [Globle getInstance].datas[indexPath.row-1];
        areaid = model.areaid;
        areacn = model.areacn;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CHSectionViewCell *cell =  (CHSectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.label.textColor = [UIColor colorWithHexString:@"148ec7" alpha:1.0f];

}

#pragma mark LongriseRouterDelegater代理回调方法
-(void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    _block = block;
    if (obj && [obj isKindOfClass:[NSMutableDictionary class]]) {
        
        NSMutableDictionary *dict = obj;
        self.title = dict[@"title"];
        self.startTime = dict[@"starttime"];
        self.endTime = dict[@"endtime"];
    }
}


@end
